<?php
/**--------------------
 * Date: 2018/2/28
 * FileName:Questions.php 
 * ProjectName:ZhiShiRongYao
 * -------------------- */


namespace app\api\controller;


use app\api\ApiBase;
use think\Db;

class Questions extends ApiBase
{
    /**
     * 获取用户pk题目
     *
     * @throws \think\exception\DbException 数据库报错
     * @return string
     */
    public function getQuestionsPk(){
        $subject_info=[];
        $is_auto_answer = input('is_auto_answer','0');
        $QuestionsModel = \think\Loader::model('QuestionsModel');
        $params = [
            'is_auto_answer'=>$is_auto_answer
        ];
        $res = $QuestionsModel->getQuestionsPk($params);
        if($res==-1){
            return $this->json_error('获取题目失败'); 
        }else if($res==0){
            return $this->json_error('题目库存不足');
        }else{
            return $this->json_success('ok', $res);
        }
        //此方法逻辑已迁移到公共模型(common/model) 
/*
        $questions_five = Db::name('questions q')
                ->join('knowledge_subject k', 'q.subject_id=k.id')
                ->where('q.status',1)
                ->field('q.id,q.title,q.answer,k.name,q.subject_id,k.parent_id as subject_cate_id')
                -> order('rand()')
                -> limit(5)
                ->select();
        
        if(count($questions_five)>=5){       
            foreach($questions_five as $k=>$v){
                $questions_ids[]=$v['id']; 
                $question_answer='';
                $question_answer=unserialize($v['answer']);
                shuffle($question_answer);
                $questions_five[$k]['answer']=$question_answer;
                if($is_auto_answer){
                    $_answer=array_rand($question_answer,1);
                    $num=[1,2,3,4,5,6];
                    $_seconds= array_rand($num,1);
                    $subject_info['user_answer'][$k]=[
                    'question_id'       =>  $v['id'],
                    'answer_id'         =>  $question_answer[$_answer]['id'],
                    'answer_val'        =>  $question_answer[$_answer]['is_right'],
                    'answer_seconds'    =>  $num[$_seconds]
                    ];
                }
            }
            $data=[
                'questions_id'   =>  implode(',', $questions_ids),
                'aid'            =>  1, //活动ID
                'user_id'        =>  $this->user_info['id'], //用户ID
                'to_user_id'     =>  2, //目标用户ID
                'create_time'    => time()
            ];
            $res=db('user_subject_pk')->insertGetId($data);
            if($res){
                $subject_info['pk_id']=$res;
                $subject_info['score_scale']= config('answer_question_time');
                $subject_info['subject']=$questions_five;
                return $this->json_success('ok', $subject_info);
            }else{
                return $this->json_error('获取题目失败'); 
            }
        }else{
            return $this->json_error('题目库存不足');
        }*/
    }
    
    /**
     * 获取用户答题记录
     *
     * @throws \think\exception\DbException 数据库报错
     * @return string
     */
    public function getQestionAnswer(){
        $pk_id = input('pk_id',0);
        $room_id = input('room_id',0);
        $user_id = $this->user_info['id'];
        $to_user_id = input('to_user_id',0);
        if(!$pk_id){
            return $this->json_error('参数错误！');
        }
        $user_answer= Db::name('user_answer_question aq')
                ->join('questions q', 'aq.qid=q.id')
                ->join('knowledge_subject k', 'q.subject_id=k.id')
                ->where('aq.pk_id',$pk_id)
                ->where('aq.user_id',$to_user_id)
                ->field('aq.*,q.title,q.answer,k.name,q.subject_id,k.parent_id as subject_cate_id')
                ->select();
                
        if($user_answer){
            
            foreach ($user_answer as $key=>$value){
                $questions_ids[]=$value['qid']; 
                $question_answer['subject'][$key]=[
                    'id'            =>  $value['qid'],
                    'title'         =>  $value['title'],
                    'subject_type'  =>  $value['name'],
                    'subject_id'    =>  $value['subject_id'],
                    'subject_cate_id'=> $value['subject_cate_id'],
                    'answer'        =>  unserialize($value['answer'])
                ];
                $question_answer['user_answer'][$key]=[
                    'question_id'       =>  $value['qid'],
                    'answer_id'         =>  $value['answer_id'],
                    'answer_val'        =>  $value['is_right'],
                    'answer_seconds'    =>  $value['answer_seconds']
                ];
            }
            $data=[
                'questions_id'   =>  implode(',', $questions_ids),
                'aid'            =>  0, //活动ID
                'user_id'        =>  $this->user_info['id'], //用户ID
                'to_user_id'     =>  $to_user_id, //目标用户ID
                'create_time'    => time()
            ];
            $pk_id=db('user_subject_pk')->insertGetId($data);

            $question_answer['pk_id']=$pk_id;
            $question_answer['score_scale']= config('answer_question_time');
            $user_info = \think\Loader::model('UserModel')->get_friends_pk_user($room_id,$user_id,$to_user_id);
            $question_answer = array_merge($question_answer,$user_info);
            return $this->json_success('ok', $question_answer);
        }else{
            return $this->json_error('参数错误！');
        }     
    }
    
        
    /**
     * 保存用户答案以及返回结果
     *
     * @throws \think\exception\DbException 数据库报错
     * @return string
     */
    public function saveUserAnswer(){
        $pk_id = input('pk_id');
        $flag_type = input('flag_type',0);//1为输，2为赢
        if(!$pk_id){
            return $this->json_error('参数错误！');
        }
        $grad_id = input('grad_id',0);
    	$score_total = input('score_total',0);//当前用户总分数
    	$to_user_score_total = input('to_user_score_total',0);//对方用户总分数
    	$answer_data = json_decode(input('answer'),TRUE);
        $subject_pk=Db::name('user_subject_pk')->where(['id'=>$pk_id])->find();
        if(!empty($subject_pk)){
            $answer_questions_id=[];
            foreach((array)$answer_data as $key => $row){
                    $answer_questions_id[$key]= $row['question_id'];
            }
            $pk_questions_id= explode(',', $subject_pk['questions_id']);
            $remain_questions_id=array_diff($pk_questions_id,$answer_questions_id);
            if($remain_questions_id){
                $map['q.id'] = ['in', implode(',', $remain_questions_id)];
                //查找出对应问题
                $questions_info = Db::name('questions q')
                ->join('knowledge_subject k', 'q.subject_id=k.id')
                ->where($map)
                ->field('q.id,q.answer,q.subject_id,k.parent_id as subject_cate_id')
                ->select();
                //用户答案
                $new_answer_data = [];
                foreach((array)$questions_info as $key => $row){
                    $answer = unserialize($row['answer']);
                    foreach($answer as $k=> $v) {
                        if($v['is_right']!=1){//正确的
                            $new_answer_data[$key]=[
                                "question_id"=>$row['id'],
                                "answer_id"=>$v['id'],
                                "answer_val"=>0,
                                "answer_seconds"=>10,
                                "subject_id"=>$row['subject_id'],
                                "subject_cate_id"=>$row['subject_cate_id']
                            ];
                            break;
                        }
                    }
                }
                $answer_data=$answer_data?array_merge($answer_data,$new_answer_data):$new_answer_data;
            }  
    	}
    	//胜负 1胜，2平，3负
        if($flag_type){//中途退出
            $is_win=$flag_type==1?3:1;
        }else{
            if($score_total>$to_user_score_total){
                $is_win = 1;
            }else if($score_total==$to_user_score_total){
                $is_win = 2;
            }else{
                $is_win = 3;
            }
        }
        $grad_info=Db::name('grad')->where(['id'=>$grad_id])->find();
        //奖励处理 
    	//判断是否使用加金币，加经验道具
    	$add_point = 0;
    	$add_exp = 0;
        $points_data=[];
        $data=[];
    	if($is_win==1){//胜
    		$add_point = $grad_id==0?0:$grad_info['reward_point'];
    		$add_exp = $grad_id==0?0:$grad_info['pass_exp'];
                $add_start=intval($this->user_info['curr_grad_start'])+1;
                $add_count_wins=intval($this->user_info['count_wins'])+1;
                //加入金币日志表
                if($add_point>0){
                    $points_data=[
                        'user_id'       =>$this->user_info['id'],
                        'user_name'     =>$this->user_info['display_name'],
                        'points'        =>$add_point,
                        'remark'        =>'对战获得金币',
                        'stage'         =>'pk',
                        'create_time'   =>time()
                    ];
                }
                
    	}else if($is_win==2){//平
                $add_point = 0;
    		$add_exp = $grad_id==0?0:$grad_info['drawn_exp'];
                $add_start=$this->user_info['curr_grad_start'];
                $add_count_wins=$this->user_info['count_wins'];
    	}else if($is_win==3){//负
                $add_point = 0;
    		$add_exp = $grad_id==0?0:$grad_info['pass_fail_exp'];
                $add_start=$this->user_info['curr_grad_start']>0?intval($this->user_info['curr_grad_start'])-1:0;
                $add_count_wins=$this->user_info['count_wins'];
    	}
        Db::startTrans();
        try{
            //经验值增加
            $add=[];
            $add['points']= intval($this->user_info['points']) + intval($add_point);
            $add['exp']= intval($this->user_info['exp']) + intval($add_exp);
            //场次
            $add['count_wins']= $add_count_wins;
            $add['count_changshu']= intval($this->user_info['count_changshu']) + 1;
            //排位赛
            if($grad_id){
                $place_num=Db::name('user_info_extend')->where(['user_id'=> $this->user_info['id']])->find();
                if($place_num){
                    //减道具
                    $extend=[];
                    $extend['exp_limit_num']=$place_num['exp_limit_num']>0?intval($place_num['exp_limit_num'])-1:'';
                    $extend['point_limit_num']=$place_num['point_limit_num']>0?intval($place_num['point_limit_num'])-1:'';
                    $extend['jf_limit_num']=$place_num['jf_limit_num']>0?intval($place_num['jf_limit_num'])-1:'';
                    if($extend){
                        Db::name('user_info_extend')->where(['user_id'=>$this->user_info['id']])->update($extend);
                    }
                    //使用道具加经验或者加金币
                    $map_prop['type']=array('neq',4);
                    $map_prop['action_type']=array('in',array(1,2));
                    $prop_list=Db::name('prop')->where($map_prop)->field('flag,reward_scale')->select();
                    $exp_scale=0;
                    $points_scale=0;
                    $data['exp_limit_time']=0;
                    $data['exp_limit_num']=0;
                    $data['point_limit_time']=0;
                    $data['point_limit_num']=0;
                    $data['jf_limit_num']=0;
                    foreach ($prop_list as $value){
                        if($place_num['exp_limit_time'] && $place_num['exp_limit_time']-time()>0){//经验时间是否过期
                            if($value['flag']=='exp_limit_time'&&$value['reward_scale']){
                                $exp_scale+=intval($value['reward_scale'])/100;
                                $data['exp_limit_time']=1;
                            }
                        }
                        if($place_num['exp_limit_num']>0){//经验场次
                            if($value['flag']=='exp_limit_num' && $value['reward_scale']){
                                $exp_scale+=intval($value['reward_scale'])/100;
                                $data['exp_limit_num']=1;
                            }
                        }
                        if($place_num['point_limit_time'] && $place_num['point_limit_time']-time()>0){//金币时间是否过期
                            if($value['flag']=='point_limit_time' && $value['reward_scale']){
                                $points_scale+= intval($value['reward_scale'])/100;
                                $data['point_limit_time']=1;
                            }
                        }
                        if($place_num['point_limit_num']>0){//金币场次
                            if($value['flag']=='point_limit_num' && $value['reward_scale']){
                                $points_scale+= intval($value['reward_scale'])/100;
                                $data['point_limit_num']=1;
                            }
                        }
                        if($place_num['jf_limit_num']>0){
                            $data['jf_limit_num']=1;
                        }
                    }
                    $add['points']+= round(intval($add_point)*$points_scale);
                    $add['exp']+= round(intval($add_exp)*$exp_scale);
                    $add_point+=round(intval($add_point)*$points_scale);
                    $add_exp+=round(intval($add_exp)*$exp_scale);
                }
                
            }
            //等级修改
            if($grad_id==$this->user_info['grad_id']){
                if($add_start>=$grad_info['pass_stars']){//星星满则进入下一级
                    $sql="select * from zp_grad where id = (select id from zp_grad where id > ".$grad_info['id']." order by id asc limit 1)";
                    $next_start=Db::query($sql);
                    $add['grad_id']=$next_start[0]['id'];
                    $add['grad_name']=$next_start[0]['name'];
                    $add['curr_grad_start']=0;
                    //获取宝箱
                    $goods_info=Db::name('user_goods')->where(['target_id'=>$grad_info['box_id'],'target_type'=>1,'user_id'=> $this->user_info['id']])->find();
                    if($goods_info){
                        $box_num=$grad_info['reward_box'];
                        $goods_data = [
                            'num'=>['exp',"num+$box_num"]
                          ];
                        Db::name('user_goods')->where(['id'=>$goods_info['id']])->update($goods_data);
                    }else{
                        $goods_data=[
                            'user_id'       => $this->user_info['id'],
                            'target_id'     => $grad_info['box_id'],
                            'target_type'   => 1,
                            'num'           => $grad_info['reward_box'],
                            'is_new'        => 1,
                            'create_time'   => time()
                        ];
                        Db::name('user_goods')->insertGetId($goods_data);
                    }
                    //用户奖励日志
                    $data_reward=[
                        'user_id'       => $this->user_info['id'],
                        'user_name'     => $this->user_info['display_name'],
                        'remark'        => '排位升级获得宝箱',
                        'stage'        => 'pwGetBox',
                        'create_time'   => time(),
                        'target_id'     => $grad_info['box_id'],
                        'target_type'   => 1
                    ];
                    Db::name('reward_log')->insertGetId($data_reward);
                }else{
                    $add['curr_grad_start']=$add_start;
                }
            }

            foreach($answer_data as $key=>$value){
                $where=[
                    'user_id'           =>$this->user_info['id'],
                    'qid'               =>$value['question_id'],
                    'answer_id'         =>$value['answer_id'],
                    'pk_id'             =>$pk_id,
                    'subject_id'        =>$value['subject_id'],
                    'subject_cate_id'   =>$value['subject_cate_id'],
                    'is_right'          =>$value['answer_val'],
                    'answer_seconds'    =>$value['answer_seconds'],
                    'create_time'       => time(),
                ];
                //选项次数
                $data_num=[];
                if($value['answer_val']){
                    $data_num['right_num']=['exp','right_num+1'];
                }else{
                    $data_num['error_num']=['exp','right_num+1'];
                }
                switch ($value['answer_id']){
                    case 1:
                        $data_num['answer1_num']=['exp','answer1_num+1'];
                        break;
                    case 2:
                        $data_num['answer2_num']=['exp','answer2_num+1'];
                        break;
                    case 3:
                        $data_num['answer3_num']=['exp','answer3_num+1'];
                        break;
                    case 4:
                        $data_num['answer4_num']=['exp','answer4_num+1'];
                        break;
                }
                Db::name('questions')->where('id',$value['question_id'])->update($data_num);
                Db::name('user_answer_question')->insertGetId($where);
            }
            Db::name('user')->where(['id'=>$this->user_info['id']])->update($add);
            if($points_data){
                Db::name('points_log')->insertGetId($points_data);
            }
            // 提交事务
            Db::commit();
            $data['is_win'] = $is_win;
            $data['add_point'] = $add_point;//此次对局获得的金币
            $data['add_exp'] = $add_exp;//此次对局获得的经验
            $data['share_points'] = config('share_game_over')['points'];//分享金币数
            return $this->json_success('ok', $data);
        } catch (\Exception $e) {
            //var_export($e);
            // 回滚事务
            Db::rollback();
            return $this->json_error('添加数据失败！');
        }
    }

    /**
     * 观战用户答案以及返回结果
     *
     * @throws \think\exception\DbException 数据库报错
     * @return string
     */
    public function gzUserAnswer(){
        $pk_id = input('pk_id');
        $flag_type = input('flag_type',0);//1为输，2为赢
        if(!$pk_id){
            return $this->json_error('参数错误！');
        }
        $grad_id = input('grad_id');
        $score_total = input('score_total',0);//当前用户总分数
        $to_user_score_total = input('to_user_score_total',0);//对方用户总分数

        //胜负 1胜，2平，3负
        if($flag_type){//中途退出
            $is_win=$flag_type==1?3:1;
        }else{
            if($score_total>$to_user_score_total){
                $is_win = 1;
            }else if($score_total==$to_user_score_total){
                $is_win = 2;
            }else{
                $is_win = 3;
            }
        }
        if($is_win==1){//胜
            $add_point = 0;//$grad_info['reward_point'];
            $add_exp = 0;//$grad_info['pass_exp'];
        }else if($is_win==2){//平
            $add_point = 0;
            $add_exp = 0;
        }else if($is_win==3){//负
            $add_point = 0;
            $add_exp = 0;
        }
        $data = [
            'is_win'=>$is_win,
            'add_point'=>$add_point,//此次对局获得的金币
            'add_exp'=>$add_exp,//此次对局获得的经验
        ];
        return $this->json_success('观战返回结果', $data);
    }

}